package com.xiaoluo.lottery.algo;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by issac on 16/4/6.
 */
public class LotterySelectImpl implements ILuckSelect{

    @Override
    public long getNextLotteryTime(long ts) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(ts);
        int hours = cal.get(Calendar.HOUR_OF_DAY);
        if (hours >= 10 && hours < 22) { // 白天10分钟开奖一次
            return AlgoUtil.getNextXMinutes(ts, 1, 10) + 80 * 1000;
        }  else if (hours >= 22 || hours < 2) { // 晚上5分钟开奖一次
            return AlgoUtil.getNextXMinutes(ts, 1, 5) + 80 * 1000;
        } else if (hours < 10 && hours >= 2){  // 等到10点开奖
            Calendar c  = Calendar.getInstance();
            c.set(Calendar.HOUR,10);
            c.set(Calendar.MINUTE,10);
            c.set(Calendar.SECOND,0);
            return c.getTimeInMillis() + 80 * 1000;
        }
        return -1;
    }

    /**
     *
     * @param timestamps  参与的时间搓列表,精确到ms
     * @param targetTime  希望兑奖的时间
     * @return 中奖结果
     */
    @Override
    public LotteryResult select(List<Long> timestamps, long targetTime) {
        LotteryResult result = new LotteryResult();
        if (timestamps == null || timestamps.size() == 0) {
            return result;
        }
        long timeTotal = 0;
        for (Long t : timestamps) {
            timeTotal += t;
        }
        JSONObject obj = null;
        try {
            obj = getResponse(targetTime);
        } catch (UnirestException e) {
            e.printStackTrace();
            result.errorDesc = "获取彩票结果错误";
            return result;
        }
        if (obj == null) {
            result.errorDesc = "没有获取到对应的开奖结果";
            return result;
        }
        System.out.println(obj);
        result.seqNo = obj.getString("expect");
        String[] codes = obj.getString("opencode").split(",");
        result.url = "http://cp.360.cn/ssccq/";
        result.codes = codes;
        timeTotal += Integer.parseInt(AlgoUtil.join(codes));
        result.select = (int)(timeTotal % timestamps.size());
        return result;
    }

    public static JSONObject getResponse(long targetTime) throws UnirestException{
        HttpResponse<JsonNode> jsonResponse = Unirest.get("http://c.apiplus.cn/newly.do?token=3db68052667445e3&code=cqssc&format=json")
                .header("accept", "application/json")
                .asJson();
        JSONArray rows = jsonResponse.getBody().getObject().getJSONArray("data");
        for (int i=0;i<rows.length();i++) {
            JSONObject obj = rows.getJSONObject(i);
            String time = obj.getString("opentime");
            if (similar(targetTime,time)) {
                return obj;
            }
        }
        return null;
    }

    public static boolean similar(long ts1,String ts2) {
        Calendar d1 = Calendar.getInstance();
        d1.setTimeInMillis(ts1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = null;
        try {
            date2 = sdf.parse(ts2);
        } catch (ParseException e) {
            e.printStackTrace();
            date2 = null;
        }
        if (date2 == null)
            return false;
        Calendar d2 = Calendar.getInstance();
        d2.setTimeInMillis(date2.getTime());
        if (d1.get(Calendar.DAY_OF_YEAR) == d2.get(Calendar.DAY_OF_YEAR) && d1.get(Calendar.HOUR_OF_DAY) == d2.get(Calendar.HOUR_OF_DAY)) {
            int m1 = d1.get(Calendar.MINUTE);
            int m2 = d2.get(Calendar.MINUTE);
            int gap;
            if (d1.get(Calendar.HOUR_OF_DAY) >= 10 && d1.get(Calendar.HOUR_OF_DAY) < 22)
                gap = 10;
            else
                gap = 5;
            if (m1 / gap == m2 / gap) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        List<Long> times = new ArrayList<>();
        for (int i=0;i<6;i++) {
            times.add(System.currentTimeMillis() - new Random().nextInt(5) * 1000 * 60);
        }
        ILuckSelect selector = new LotterySelectImpl();
        long start = System.currentTimeMillis();
        long targetTime = selector.getNextLotteryTime(System.currentTimeMillis());
        Date d = new Date(targetTime);
        System.out.println(times.toString());
        System.out.println(d);
        LotteryResult result = selector.select(times, targetTime);
        System.out.println("cost "+(System.currentTimeMillis() - start)+"ms "+result.toString());
    }
}
